import { defineNuxtPlugin } from "nuxt/app";
import { useGlobalStore } from "~~/store/global";
import { useDevicesCookie } from "~/utils/cookie";
import { DANA_PACKAGE_ID } from "../config/index";
import { useEnvConfigInfo } from "~/utils/index";

export default defineNuxtPlugin(() => {
  const headers = useRequestHeaders([
    "host",
    "token",
    "package-id",
    "language",
    "statebarheight",
    "isiphonex",
  ]);
  const globalStore = useGlobalStore();
  const cookie = useDevicesCookie();

  // const { WEB_NODE_ENV = "prod" } = useRuntimeConfig().public;
  // console.log(WEB_NODE_ENV, "-服务端：headers--", headers);
  // 1. 获取服务端参数
  if (headers["package-id"]) {
    // console.log('--headers--',headers);
   globalStore.$patch((state) => {
      if (headers.token) {
        state.token = headers.token;
      }
      state.packageId = headers["package-id"]!;
      state.language = headers["language"] ?? "en";
      state.statusBarHeight = Number(headers.statebarheight) ?? 0;
      state.isiOS = headers["package-id"]!.includes("online-ios");
      state.IsIphoneX = headers["isiphonex"]
        ? headers["isiphonex"] == 1
        : false;
    });

    cookie.setInfo({
      token: headers.token || cookie.token,
      packageId: headers["package-id"] ?? DANA_PACKAGE_ID.value,
      language: headers["language"] ?? "en",
      statusBarHeight: headers.statebarheight ?? "0",
    });
  }
  // 2. 调试模式 dev ，配置默认参数
  if (process.env.NODE_ENV == "development") {
    const route = useRoute();
    let route_token = "";
    if (route.query && route.query.token) {
      route_token = route.query.token as string;
      console.log("serve: URL链接 -- 传入token:", route_token);
    }
   globalStore.$patch((state) => {
      state.token = route_token || useEnvConfigInfo().token;
      state.statusBarHeight = 44; // 本地开发,模拟状态栏高度 iphone x
    });
    console.log("serve: 使用默认 token");
  }
});
